<template>
  <div class="monitor-container">
    <div class="board">
      <div class="dashboard-box">
        <div
          id="cpu_board"
          class="dashboard"
        />

        <fks-tooltip
          :content="LANG.ALERT_SETTING"
          placement="bottom"
        >
          <i
            class="fks-icon-setting-solid"
            @click="showAlertPage('cpu')"
          />
        </fks-tooltip>
        <div class="dash-title">
          {{ LANG.CPU_UTILIZATIONRATE }}
        </div>
      </div>
      <div
        class="dashboard-box"
      >
        <div
          id="mem_board"
          class="dashboard"
        />
        <fks-tooltip
          :content="LANG.ALERT_SETTING"
          placement="bottom"
        >
          <i
            class="fks-icon-setting-solid"
            @click="showAlertPage('mem')"
          />
        </fks-tooltip>

        <div class="dash-title">
          {{ LANG.MEM_UTILIZATIONRATE }}
        </div>
      </div>
      <div
        class="dashboard-box"
      >
        <div
          id="disk_board"
          class="dashboard"
        />
        <fks-tooltip
          :content="LANG.ALERT_SETTING"
          placement="bottom"
        >
          <i
            class="fks-icon-setting-solid"
            @click="showAlertPage('disk')"
          />
        </fks-tooltip>

        <div class="dash-title">
          {{ LANG.DISK_UTILIZATIONRATE }}
        </div>
      </div>
    </div>
    <div class="line-chart">
      <div
        style="position: absolute; z-index: 99; left: 16px; line-height: 36px"
      >
        {{ LANG.CPU_UTILIZATIONRATE }}
      </div>
      <div style="position: absolute; z-index: 99; right: 16px">
        <fks-select
          v-model="cpu_time"
          :placeholder="LANG.PLEASE_SELECT"
          style="width: 160px; height: 36px"
          @change="getCpuLineChart()"
        >
          <fks-option
            v-for="item in cpuTimes"
            :key="item.code"
            :label="item[$lang]"
            :value="item.code"
          />
        </fks-select>
        <fks-button
          style="margin-left: 32px; cursor: pointer"
          @click="getCpuLineChart"
        >
          <i class="fks-icon-swap" />
        </fks-button>
      </div>
      <div
        id="cpu_line_chart"
        v-loading="cpuLoading"
        style="width: 95%; height: 340px"
      />
    </div>
    <div class="line-chart">
      <div
        style="position: absolute; z-index: 99; left: 16px; line-height: 36px"
      >
        {{ LANG.MEM_UTILIZATIONRATE }}
      </div>
      <div style="position: absolute; z-index: 99; right: 16px">
        <fks-select
          v-model="mem_time"
          :placeholder="LANG.PLEASE_SELECT"
          style="width: 160px; height: 36px"
          @change="getMemLineChart()"
        >
          <fks-option
            v-for="item in memTimes"
            :key="item.code"
            :label="item[$lang]"
            :value="item.code"
          />
        </fks-select>
        <fks-button
          style="margin-left: 32px; cursor: pointer"
          @click="getMemLineChart"
        >
          <i class="fks-icon-swap" />
        </fks-button>
      </div>
      <div
        id="mem_line_chart"
        v-loading="memLoading"
        style="width: 95%; height: 340px"
      />
    </div>
    <div class="disk-container">
      <div style="display: flex">
        <div style="flex: 1; line-height: 36px">
          {{ LANG.DISK_UTILIZATIONRATE }}
        </div>
        <fks-tooltip
          :content="LANG.LINE_CHART"
          placement="bottom"
        >
          <fks-button
            v-if="diskShowType == 'allList'"
            @click="getDiskLineChart"
          >
            <i class="fks-icon-line-chart" />
          </fks-button>
        </fks-tooltip>

        <div v-if="diskShowType != 'allList'">
          <fks-select
            v-model="disk_time"
            :placeholder="LANG.PLEASE_SELECT"
            style="width: 160px; height: 36px"
            @change="
              current_diskName == 'totalDisk'
                ? getDiskLineChart()
                : getPartLineChart()
            "
          >
            <fks-option
              v-for="item in memTimes"
              :key="item.code"
              :label="item[$lang]"
              :value="item.code"
            />
          </fks-select>
          <fks-tooltip
            :content="LANG.DASH_BOARD"
            placement="bottom"
          >
            <fks-button
              v-if="diskShowType == 'allDetail'"
              style="margin-left: 32px"
              @click="backDiskList"
            >
              <i class="fks-icon-dashboard" />
            </fks-button>
          </fks-tooltip>
          <fks-button
            v-if="diskShowType == 'partDetail'"
            style="margin-left: 32px"
            @click="backDiskList"
          >
            <i class="fks-icon-reject" />
          </fks-button>
        </div>
      </div>
      <div
        v-if="diskShowType == 'allList'"
        style="min-height: 0; transition: min-height 1s ease .1s"
      >
        <div v-if="diskPartList.length != 0">
          <div
            v-for="disk in diskPartList"
            :key="disk.id"
            class="disk_part_item"
            @click="getPartDetail(disk)"
          >
            <div class="disk_label">
              {{ disk.diskDirName + LANG.DISC }}
            </div>
            <div style="display: inline-block; width: 60%">
              <fks-progress
                :text-inside="true"
                :stroke-width="20"
                :percentage="Number((disk.diskUsedRate * 100).toFixed(0))"
                :color="
                  Number((disk.diskUsedRate * 100).toFixed(0)) < 40
                    ? '#36C4C4'
                    : Number((disk.diskUsedRate * 100).toFixed(0)) < 80
                      ? '#FFC12E'
                      : '#FF4D4F'
                "
              />
            </div>
          </div>
        </div>
        <div
          v-else
          style="width: 100%; line-height: 260px; text-align: center"
        >
          {{ LANG.NO_DATA }}
        </div>
      </div>
      <div v-if="diskShowType == 'allDetail'">
        <div
          id="disk_line_chart"
          v-loading="diskLoading"
          style="width: 95%; height: 300px"
        />
      </div>
      <div
        v-if="diskShowType == 'partDetail'"
        style="display: flex; align-items: center; min-height: 260px"
      >
        <div class="part_left">
          <div>
            <div
              id="part_dashboard"
              style="width: 120px; height: 120px"
            />
            <div class="total_text">
              <span style="font-size: 14px; color: #999">{{ LANG.TOTAL }}</span><span style="color: #2f53ea">{{ part_diskTotal + LANG.G }}</span>
            </div>
          </div>
          <div style="width: 90px; margin: 0 16px">
            <div style="font-size: 24px">
              {{ current_diskName + LANG.DISC }}
            </div>
            <div
              class="part_num"
              :style="{
                color:
                  part_diskUsedRate < 40
                    ? '#36C4C4'
                    : part_diskUsedRate < 80
                      ? '#FFC12E'
                      : '#FF4D4F'
              }"
            >
              {{ part_diskUsedRate + '%' }}
            </div>
          </div>
        </div>
        <div
          id="part_line_chart"
          v-loading="partLineLoading"
          style="width: 70%; height: 260px"
        />
        <fks-button
          class="fks-icon-arrow-right"
          size="mini"
          style="cursor: pointer"
          @click="nextPartDisk"
        />
      </div>
    </div>
    <warn-page
      v-if="visible"
      :visible.sync="visible"
      :warning-type="warningType"
    />
  </div>
</template>
<script>
import { ENUM } from '@/store/State/stateTypes'
import WarnPage from './components/warningPage'
import Mix from '@/mixins/module'
import * as echarts from 'echarts/core'
import { LineChart, GaugeChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([
  LineChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  CanvasRenderer,
  LegendComponent,
  GaugeChart
])
import {
  getCPUData,
  getMEMData,
  getDiskPartData,
  getDiskAllRate,
  getCPUChartData,
  getMEMChartData,
  getDiskData,
  getCPUAlert,
  getDiskAlert,
  getMEMAlert
} from './api'
export default {
  name: 'Monitor',
  components: { WarnPage },
  mixins: [Mix],
  data() {
    return {
      dashBoardOption: {
        series: [
          {
            name: '',
            type: 'gauge',
            progress: {
              show: true,
              width: 10,
              itemStyle: {
                color: '#36C4C4'
              }
            },
            axisLine: {
              lineStyle: {
                width: 10
              }
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              show: false
            },
            anchor: {
              show: true,
              showAbove: true,
              size: 16,
              itemStyle: {
                borderWidth: 6,
                borderColor: '#36C4C4'
              }
            },
            pointer: {
              length: '80%',
              itemStyle: {
                color: '#36C4C4'
              }
            },
            detail: {
              valueAnimation: true,
              fontSize: 30,
              offsetCenter: [0, '70%'],
              formatter: '{value}%',
              color: '#36C4C4'
            },
            data: [
              {
                value: 0
              }
            ]
          }
        ]
      },
      lineOption: {
        tooltip: {
          trigger: 'axis'
        },
        color: '#399aea',
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            interval: 'auto'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: []
      },
      cpuLoading: false,
      memLoading: false,
      diskLoading: false,
      partLineLoading: false,
      cpu_time: '5',
      mem_time: '60',
      disk_time: '60',
      cpuLineChart: '',
      memLineChart: '',
      diskLineChart: '',
      partLineChart: '',
      diskPartList: [],
      diskShowType: 'allList',
      current_diskName: 'totalDisk',
      part_diskUsedRate: 0,
      part_diskTotal: 0,
      visible: false,
      warningType: '',
      timer: ''
    }
  },
  computed: {
    cpuTimes() {
      return this.$store.state[ENUM].cpuTimes || []
    },
    memTimes() {
      return this.$store.state[ENUM].memTimes || []
    }
  },
  mounted() {
    window.addEventListener('resize', () => {
      this.cpuLineChart.resize()
      this.memLineChart.resize()
      if (this.diskLineChart) {
        this.diskLineChart.resize()
      }
      if (this.partLineChart) {
        this.partLineChart.resize()
      }
    })
    this.getCpuRate()
    this.getMemRate()
    this.getDiskRate()
    this.getCpuLineChart()
    this.getMemLineChart()
    this.getAllPartDiskRate()
    this.timer = setInterval(() => {
      this.getCpuRate()
      this.getMemRate()
      this.getDiskRate()
      this.getAllPartDiskRate()
    }, 10000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    //根据数值设置仪表盘颜色
    setRateColor(option, val) {
      if (val < 40) {
        option.series[0].progress.itemStyle.color = '#36C4C4'
        option.series[0].anchor.itemStyle.borderColor = '#36C4C4'
        option.series[0].pointer.itemStyle.color = '#36C4C4'
        option.series[0].detail.color = '#36C4C4'
      } else if (val < 80) {
        option.series[0].progress.itemStyle.color = '#FFC12E'
        option.series[0].anchor.itemStyle.borderColor = '#FFC12E'
        option.series[0].pointer.itemStyle.color = '#FFC12E'
        option.series[0].detail.color = '#FFC12E'
      } else {
        option.series[0].progress.itemStyle.color = '#FF4D4F'
        option.series[0].anchor.itemStyle.borderColor = '#FF4D4F'
        option.series[0].pointer.itemStyle.color = '#FF4D4F'
        option.series[0].detail.color = '#FF4D4F'
      }
    },
    //监控cpu使用率
    getCpuRate() {
      getCPUData()
        .then((res) => {
          if (res.status) {
            let cpuDashBoard = echarts.init(
              document.getElementById('cpu_board')
            )
            let cpudata = parseFloat(res.data.cpuUsedRate * 100).toFixed(0)
            let cpuDashOption = JSON.parse(JSON.stringify(this.dashBoardOption))
            cpuDashOption.series[0].data[0].value = cpudata
            this.setRateColor(cpuDashOption, cpudata)
            cpuDashBoard.setOption(cpuDashOption)
          }
        })
        .catch(() => {})
    },
    //监控内存使用率
    getMemRate() {
      getMEMData()
        .then((res) => {
          if (res.status) {
            let memDashBoard = echarts.init(
              document.getElementById('mem_board')
            )
            let memdata = parseFloat(res.data.memUsedRate * 100).toFixed(0)
            let memDashOption = JSON.parse(JSON.stringify(this.dashBoardOption))
            memDashOption.series[0].data[0].value = memdata
            this.setRateColor(memDashOption, memdata)
            memDashBoard.setOption(memDashOption)
          }
        })
        .catch(() => {})
    },
    //监控磁盘使用率
    getDiskRate() {
      getDiskAllRate(this.current_diskName)
        .then((res) => {
          if (res.status) {
            let diskDashBoard = echarts.init(
              document.getElementById('disk_board')
            )
            let diskAllRate = parseFloat(res.data.diskUsedRate * 100).toFixed(0)
            let diskDashOption = JSON.parse(
              JSON.stringify(this.dashBoardOption)
            )
            diskDashOption.series[0].data[0].value = diskAllRate
            this.setRateColor(diskDashOption, diskAllRate)
            diskDashBoard.setOption(diskDashOption)
          }
        })
        .catch(() => {})
    },
    //绘制cpu折线图
    getCpuLineChart() {
      this.cpuLoading = true
      getCPUChartData(this.cpu_time)
        .then((res) => {
          this.cpuLineChart = echarts.init(
            document.getElementById('cpu_line_chart')
          )
          let cpuLineOption = JSON.parse(JSON.stringify(this.lineOption))
          cpuLineOption.legend = {
            data: [this.LANG.ALL_USED, this.LANG.USER, this.LANG.SYSTEM],
            icon: 'rect',
            orient: 'horizontal',
            right: '  200',
            top: '10',
            itemHeight: 8,
            itemWidth: 16
          }
          cpuLineOption.color = ['#399aea', '#5ad8e5', '#addd52']
          cpuLineOption.series = [
            {
              name: this.LANG.ALL_USED,
              data: [],
              type: 'line',
              smooth: true
            },
            {
              name: this.LANG.USER,
              data: [],
              type: 'line',
              smooth: true
            },
            {
              name: this.LANG.SYSTEM,
              data: [],
              type: 'line',
              smooth: true
            }
          ]
          if (res.status) {
            let totalRate = res.data[0].totalRate.map((item) => {
              return item.toFixed(2)
            })
            let userRate = res.data[0].userRate.map((item) => {
              return item.toFixed(2)
            })
            let sysRate = res.data[0].sysRate.map((item) => {
              return item.toFixed(2)
            })
            cpuLineOption.series[0].data = totalRate
            cpuLineOption.series[1].data = userRate
            cpuLineOption.series[2].data = sysRate
            cpuLineOption.xAxis.data = res.data[1].CreateDate
            this.cpuLineChart.clear()
            this.cpuLineChart.setOption(cpuLineOption)
            this.cpuLoading = false
          } else {
            cpuLineOption.series[0].data = []
            cpuLineOption.series[1].data = []
            cpuLineOption.series[2].data = []
            cpuLineOption.xAxis.data = []
          }
        })
        .catch(() => {})
    },
    //绘制内存折线图
    getMemLineChart() {
      this.memLoading = true
      getMEMChartData(this.mem_time)
        .then((res) => {
          if (res.status) {
            this.memLineChart = echarts.init(
              document.getElementById('mem_line_chart')
            )
            let memLineOption = JSON.parse(JSON.stringify(this.lineOption))
            memLineOption.series = [
              {
                name: this.LANG.MEM_UTILIZATIONRATE,
                data: [],
                type: 'line',
                smooth: true
              }
            ]
            res.data.forEach((item) => {
              memLineOption.xAxis.data.push(item.createDate)
              let mem_data = parseFloat(item.memUsedRate * 100).toFixed(2)
              memLineOption.series[0].data.push(mem_data)
            })
            this.memLineChart.clear()
            this.memLineChart.setOption(memLineOption)
            this.memLoading = true
          }
        })
        .catch(() => {})
    },
    //获取磁盘分盘列表
    getAllPartDiskRate() {
      getDiskPartData()
        .then((res) => {
          if (res.status) {
            this.diskPartList = res.data
          }
        })
        .catch(() => {
          this.diskPartList = []
        })
    },
    //绘制磁盘折线图
    getDiskLineChart() {
      this.diskShowType = 'allDetail'
      this.diskLoading = true
      this.current_diskName = 'totalDisk'
      let params = {
        name: this.current_diskName,
        time: this.disk_time
      }
      getDiskData(params)
        .then((res) => {
          if (res.status) {
            this.diskLineChart = echarts.init(
              document.getElementById('disk_line_chart')
            )
            let diskLineOption = JSON.parse(JSON.stringify(this.lineOption))
            diskLineOption.grid.top = '10%'
            diskLineOption.series = [
              {
                name: this.LANG.DISK_UTILIZATIONRATEd,
                data: [],
                type: 'line',
                smooth: true
              }
            ]
            res.data.forEach((item) => {
              diskLineOption.xAxis.data.push(item.createDate)
              let disk_data = parseFloat(item.diskUsedRate * 100).toFixed(2)
              diskLineOption.series[0].data.push(disk_data)
            })
            this.diskLineChart.clear()
            this.diskLineChart.setOption(diskLineOption)
            this.diskLoading = false
          }
        })
        .catch(() => {})
    },
    //返回磁盘分盘列表
    backDiskList() {
      if (this.diskShowType == 'allDetail') {
        echarts.init(document.getElementById('disk_line_chart')).dispose()
      }
      this.diskShowType = 'allList'
    },
    // 获取分盘详细信息
    getPartDetail(disk) {
      this.diskShowType = 'partDetail'
      this.$nextTick(() => {
        let partDashBoard = echarts.init(
          document.getElementById('part_dashboard')
        )
        let partDiskOption = JSON.parse(JSON.stringify(this.dashBoardOption))
        partDiskOption.series[0].anchor.size = 6
        partDiskOption.series[0].anchor.itemStyle.borderWidth = 3
        partDiskOption.series[0].pointer.width = 2
        partDiskOption.series[0].pointer.length = '60%'
        partDiskOption.series[0].detail.fontSize = 16
        partDiskOption.series[0].data[0].value = parseFloat(
          disk.diskUsedRate * 100
        ).toFixed(0)
        this.part_diskUsedRate = parseFloat(disk.diskUsedRate * 100).toFixed(0)
        this.setRateColor(partDiskOption, this.part_diskUsedRate)
        this.current_diskName = disk.diskDirName
        this.part_diskTotal = parseFloat(disk.diskTotal / 1000000000).toFixed(0)
        partDashBoard.setOption(partDiskOption)
        this.getPartLineChart()
      })
    },
    //绘制各分盘折线图
    getPartLineChart() {
      this.partLineLoading = true
      let params = {
        name: this.current_diskName,
        time: this.disk_time
      }
      getDiskData(params)
        .then((res) => {
          if (res.status) {
            this.partLineChart = echarts.init(
              document.getElementById('part_line_chart')
            )
            let partLineOption = JSON.parse(JSON.stringify(this.lineOption))
            partLineOption.grid.top = '10%'
            partLineOption.series = [
              {
                data: [],
                type: 'line',
                smooth: true,
                areaStyle: {
                  opacity: 0.3
                }
              }
            ]
            res.data.forEach((item) => {
              partLineOption.xAxis.data.push(item.createDate)
              let disk_data = parseFloat(item.diskUsedRate * 100).toFixed(2)
              partLineOption.series[0].data.push(disk_data)
            })
            this.partLineChart.clear()
            this.partLineChart.setOption(partLineOption)
            this.partLineLoading = false
          }
        })
        .catch(() => {})
    },
    //查看下一个分盘折线图
    nextPartDisk() {
      for (let i = 0; i < this.diskPartList.length; i++) {
        if (this.diskPartList[i].diskDirName == this.current_diskName) {
          if (i == this.diskPartList.length - 1) {
            this.getPartDetail(this.diskPartList[0])
          } else {
            this.getPartDetail(this.diskPartList[i + 1])
          }
        }
      }
    },
    //打开报警弹窗
    showAlertPage(type) {
      this.warningType = type
      this.visible = true
    }
  }
}
</script>
<style lang="scss" scoped>
.monitor-container {
  background-color: #f1f2f6 !important;
}
.board {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  >div {
    flex: 1 0 150px;
    min-height: 150px;
    margin: 10px;
  }
}
.dashboard-box {
  position: relative;
  display: flex;
  flex: 1;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 0;
  height: 300px;
  padding-bottom: 32px;
  background: #fff;

  .dashboard {
    width: 300px;
    height: 300px;
    >div {
      margin: auto;
    }
  }
  .fks-icon-setting-solid {
    position: absolute;
    top: 16px;
    right: 16px;
    width: 16px;
    height: 16px;
    color: #989da3;
    opacity: .3;
    cursor: pointer;
  }

  .dash-title {
    margin-top: -48px;
    font-size: 24px;
    color: #333;
  }
}

.line-chart,
.disk-container {
  position: relative;
  width: 100%;
  min-width: 680px;
  padding: 16px;
  margin: 16px 0;
  background: #fff;
}

::v-deep .disk-container {
  margin-bottom: 0;

  .disk_label {
    display: inline-block;
    width: 64px;
    margin: 0 32px;
    line-height: 60px;
  }

  .disk_part_item {
    display: inline-block;
    width: 50%;
    cursor: pointer;
  }

  .total_text {
    width: 120px;
    margin-top: -16px;
    text-align: center;
  }

  .part_num {
    font-weight: bold;
    font-size: 34px;
  }

  .part_left {
    display: flex;
    align-items: center;
    margin: 0 32px;
  }

  .fks-button {
    cursor: pointer;
  }
}
</style>